package com.jams.goodox.activity.wallet;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hangzhou.jin.customview.SuperText;
import com.hangzhou.jin.customview.TailsTextView;
import com.hangzhou.jin.customview.TitleView;
import com.jams.goodox.BasePayActivity;
import com.jams.goodox.R;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.adapter.MineWalletAdapter;
import com.jams.goodox.constant.Constants;
import com.jams.goodox.constant.H5UrlConstants;
import com.jams.goodox.constant.UamaPayCode;
import com.jams.goodox.entity.PayWayBean;
import com.jams.goodox.entity.RechargeFeedbackBean;
import com.jams.goodox.entity.RechargeRedPacket;
import com.jams.goodox.entity.RechargeRedPacketsInfo;
import com.jams.goodox.entity.RechargeThirdPayResultBean;
import com.jams.goodox.entity.StringBean;
import com.jams.goodox.entity.User;
import com.jams.goodox.entity.pay.AiliPayBean;
import com.jams.goodox.entity.pay.WeChatPayBean;
import com.jams.goodox.listen.CheckPayPassword;
import com.jams.goodox.listen.PayListener;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.MineService;
import com.jams.goodox.utils.MessageDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by Jin on 2016/12/27.
 * Description 我的钱包
 */
public class MineWalletActivity extends BasePayActivity implements PayConstants {

    @Bind(R.id.title_view)
    TitleView titleView;
    @Bind(R.id.input_money)
    EditText mInputMoney;
    @Bind(R.id.red_packet_hint)
    TailsTextView mRedPacketHint;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.submit)
    TextView mSubmit;
    @Bind(R.id.balance)
    TextView balanceView;
    @Bind(R.id.mask)
    RelativeLayout successMask;
    @Bind(R.id.ok)
    SuperText successOK;

    // 按钮是否可以点击的状态
    boolean couldClick = false;

    // 支付种类list
    private List<Integer> listPayWay;
    // 红包数据
    private List<RechargeRedPacket> list;
    // 充值id
    private String rechargeId;
    // 充值活动id
    private String rechargeActivityId = "";

    private MineWalletAdapter mAdapter;
    // 余额
    private double balance;
    private int from;//0:个人“我的”页面 1：企业账号首页


    @Override
    protected int getLayoutId() {
        return R.layout.mine_wallet;
    }

    @Override
    protected void init() {
        from  = getIntent().getIntExtra("from",0);
        setTitleVisibility(false);
        initInputMoneyBtn();
        initRecyclerView();
        if(from == 0){
            titleView.setTitle(getString(R.string.mine_wallet));
        }else{
            titleView.setTitle("企业账户");
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestBalance();
    }

    private void requestBalance() {
        enqueue(createCallService(MineService.class).balance(null), new RetrofitCallbackListener<StringBean>() {
            @Override
            public void onSuccess(Call<StringBean> call, StringBean result) {
                try {
                    balance = Double.parseDouble(result.getData());
                } catch (NumberFormatException e) {
                    balance = 0.00;
                }
                balanceView.setText(User.getPriceString(balance));
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    private void initRecyclerView() {
        // 设置7dp的间隙
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.margin_size_small7);
        // 禁止滚动
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        recyclerView.addItemDecoration(new MineWalletSpaceItemDecoration(spacingInPixels));

        mAdapter = new MineWalletAdapter(null);
        recyclerView.setAdapter(mAdapter);

        list = new ArrayList<>();
        initRedPacketList();

        listPayWay = new ArrayList<>();
        initPayWay();

        bindWXResultBroadcast();
    }

    /**
     * 加载红包和赠送
     */
    private void initRedPacketList() {
        enqueue(createCallService(MineService.class).rechargeActivity(), new RetrofitCallbackListener<RechargeFeedbackBean>() {
            @Override
            public void onSuccess(Call<RechargeFeedbackBean> call, RechargeFeedbackBean result) {
                rechargeActivityId = result.getData().getRechargeActivityId();
                list = result.getData().getRechargeRedpacketList();
                if (list != null) {
                    recyclerView.setVisibility(list.size() == 0 ? View.GONE : View.VISIBLE);
                    mAdapter.setNewData(list);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    /**
     * 加载可以使用的第三方支付方式
     */
    private void initPayWay() {
        enqueue(createCallService(MineService.class).types(), new RetrofitCallbackListener<PayWayBean>() {
            @Override
            public void onSuccess(Call<PayWayBean> call, PayWayBean result) {
                listPayWay = result.getData();
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @OnClick({R.id.xie_yi, R.id.submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.xie_yi:
                Bundle b = new Bundle();
                b.putString(SimpleHtmlActivity.URL, H5UrlConstants.H5_Agreement);
                b.putString(SimpleHtmlActivity.TITLE, "安全协议");
                qBackToActivity(SimpleHtmlActivity.class, b);
                break;
            case R.id.submit:
                if (couldClick) {
                    String in = mInputMoney.getText().toString();
                    dialog(in);
                }
                break;
        }
    }

    /**
     * 弹出支付窗
     *
     * @param in 充值金额
     */
    public void dialog(final String in) {
        closeKeyboard();
        if(TextUtils.isEmpty(in)){
            return;
        }
        if (checkHasSetPassword()) {
            if (null != listPayWay) {
                // 弹出支付窗
                Dialog dialog = MessageDialog.showPaymentBottomMenu(mContext, listPayWay, new MessageDialog.MenuDialogOnItemClickListener() {

                    @Override
                    public void onItemClick(int index) {
                        thirdPay(in, index);
                    }
                });

                // 弹窗消失刷新红包列表，为了让高亮的那个变回原来的颜色
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (null != list)
                            mAdapter.setNewData(list);
                    }
                });
            }
        } else {
            // 清空list选中的状态
            if (null != list)
                mAdapter.setNewData(list);
        }
    }

    /**
     * 检查是否设置密码
     */
    private boolean checkHasSetPassword() {
        return new CheckPayPassword(MineWalletActivity.this, SetPayPassword2Activity.COME_MineWalletActivity).checkHasSetPassword();
    }


    /**
     * 第三方支付
     *
     * @param in    充值金额
     * @param index 充值方式
     */
    private void thirdPay(final String in, final int index) {
        enqueue(createCallService(MineService.class).recharge(in, rechargeActivityId), new RetrofitCallbackListener<RechargeThirdPayResultBean>() {
            @Override
            public void onSuccess(Call<RechargeThirdPayResultBean> call, RechargeThirdPayResultBean result) {
                rechargeId = result.getData().getRechargeId();
                switch (index){
                    case ZFB:
                        AiliPayBean ailiPayBean = new AiliPayBean();
                        ailiPayBean.setId(rechargeId);
                        ailiPayBean.setCode(result.getData().getSerialNumber());
                        ailiPayBean.setType(Constants.PayType.Type_Recharge);
                        ailiPayBean.setMoneyCharge(in);
                        ailiPayBean.setTitle("充值");
                        payByAili(ailiPayBean, new PayListener() {
                            @Override
                            public void payResult(int status, String msg) {
                                switch (status) {
                                    case UamaPayCode.PAY_SUCCESS:
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadRedPacketDialog();
                                            }
                                        });
                                        break;
                                }
                            }
                        });
                        break;
                    case WX:
                        WeChatPayBean weChatPayBean = new WeChatPayBean();
                        weChatPayBean.setOrderId(rechargeId);
                        weChatPayBean.setPayType(Constants.PayType.Type_Recharge);
                        payByWeChat(weChatPayBean, new PayListener() {
                            @Override
                            public void payResult(int status, String msg) {
                                switch (status) {
                                    case UamaPayCode.PAY_SUCCESS:
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                loadRedPacketDialog();
                                            }
                                        });
                                        break;
                                }
                            }
                        });
                        break;
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }
    /**
     * 充值成功返回后调用的弹窗
     */
    private void loadRedPacketDialog() {
        enqueue(createCallService(MineService.class).redPacketByRechargeId(rechargeId), new RetrofitCallbackListener<RechargeRedPacketsInfo>() {
            @Override
            public void onSuccess(Call<RechargeRedPacketsInfo> call, RechargeRedPacketsInfo result) {
                if (result.getData().size() == 0) {
                    // 显示充值成功窗口
                    successMask.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 设置空的点击事件为了覆盖底层的点击事件
                        }
                    });
                    successMask.setVisibility(View.VISIBLE);
                    successOK.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            successMask.setVisibility(View.GONE);
                        }
                    });
                } else {
                    // 弹出红包列表窗口
                    MessageDialog.showRedPackageList(mContext, result.getData(), null);
                }
            }

            @Override
            public void onError(String msg) {

            }
        });
    }

    @Override
    protected void doBackThing() {
        super.doBackThing();
    }

    /**
     * 初始化输入框联动效果
     */
    private void initInputMoneyBtn() {
        final Drawable res1 = ContextCompat.getDrawable(mContext, R.drawable.bottom_btn_2dp_main);
        final Drawable res2 = ContextCompat.getDrawable(mContext, R.drawable.bottom_btn_2dp_grey);
        // 当输入框有内容时，按钮变色
        mInputMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {

                    // 拦截内容为空是，输入0的操作
                    if (s.length() == 1 && TextUtils.equals(s.toString(), "0")) {
                        mInputMoney.setText("");
                        return;
                    }

                    couldClick = s.length() > 0;
                    mSubmit.setBackground(couldClick ? res1 : res2);
                    mSubmit.setTextColor(couldClick ?ContextCompat.getColor(mContext,R.color.font_main):ContextCompat.getColor(mContext,R.color.white));
                    double input;
                    try {
                        input = Double.parseDouble(s.toString());
                    } catch (NumberFormatException e) {
                        input = 0.00;
                    }

                    // 输入内容值为0的时候， 设置不能点击
                    if (input == 0) {
                        couldClick = false;
                        mSubmit.setBackground(res2);
                        mSubmit.setTextColor(ContextCompat.getColor(mContext,R.color.white));
                        return;
                    }

                    // 充值充多少送多少的联动处理
                    if (null != list) {
                        if (list.size() > 0) {
                            int index = 0;
                            double min = Integer.MAX_VALUE;
                            for (int i = 0; i < list.size(); i++) {
                                RechargeRedPacket rrp = list.get(i);
                                double d = Double.parseDouble(rrp.getRechargeMoney());

                                // 差值
                                double value = input - d;
                                // 若差值相比前面更小，则更新差值
                                if (value >= 0 && value < min) {
                                    index = i;
                                    min = value;
                                }
                            }

                            // 根据结果刷新显示
                            mRedPacketHint.setVisibility(min != Integer.MAX_VALUE ? View.VISIBLE : View.INVISIBLE);
                            // 最小的那个差值不是默认值，则说明得到了一个充值送的好包值,显示之
                            if (min != Integer.MAX_VALUE) {
                                mRedPacketHint.setText(list.get(index).getRedPacketMoney());
                            }
                        }
                    }
                } else {
                    // 当输入框没内容的时候，隐藏赠送的文本
                    mRedPacketHint.setVisibility(View.INVISIBLE);

                    couldClick = s.length() > 0;
                    mSubmit.setBackground(couldClick ? res1 : res2);
                    mSubmit.setTextColor(couldClick ?ContextCompat.getColor(mContext,R.color.font_main):ContextCompat.getColor(mContext,R.color.white));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
}
